<template>
  <div
    ref="chartRef"
    class="echarts-container"
    :style="{
      width: `${width}%`,
      height: `${height}%`
    }"
  ></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  options: {
    type: Object,
    default: () => ({})
  },
  autoResize: {
    type: Boolean,
    default: true
  },
  width: {
    type: Number,
    default: 100,
    validator: (value: number) => value > 0 && value <= 100
  },
  height: {
    type: Number,
    default: 100,
    validator: (value: number) => value > 0 && value <= 100
  }
});

const chartRef = ref<HTMLDivElement | null>(null);
const chartInstance = ref<echarts.ECharts | null>(null);

const initChart = () => {
  if (!chartRef.value) return;

  // 确保容器有尺寸
  if (chartRef.value.clientWidth === 0 || chartRef.value.clientHeight === 0) {
    console.warn('ECharts 容器尺寸为0，无法初始化');
    return;
  }

  chartInstance.value = markRaw(echarts.init(chartRef.value));
  updateChart();
  handleResize(); // 初始化后立即调整尺寸
};

const updateChart = () => {
  if (!chartInstance.value) return;
  chartInstance.value.setOption({
    ...props.options,
    grid: {
      // 确保grid配置填充容器
      top: 20,
      right: 20,
      bottom: 20,
      left: 20,
      containLabel: true
    }
  });
};

const handleResize = () => {
  nextTick(() => {
    chartInstance.value?.resize({
      animation: {
        duration: 300
      }
    });
  });
};

watch(
  () => props.options,
  () => updateChart(),
  { deep: true }
);

onMounted(() => {
  nextTick(() => {
    initChart();
    if (props.autoResize) {
      window.addEventListener('resize', handleResize);
    }
  });
});

onBeforeUnmount(() => {
  if (chartInstance.value) {
    chartInstance.value.dispose();
  }
  window.removeEventListener('resize', handleResize);
});

defineExpose({
  getInstance: () => chartInstance.value,
  resize: handleResize
});
</script>

<style scoped>
.echarts-container {
  display: block;
  min-width: 100%;
  min-height: 100%;
}
</style>
